package com.hupu.jrs.widget

import android.content.Context
import android.graphics.drawable.BitmapDrawable
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow
import com.hupu.jrs.R

class PagePicker @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : PopupWindow(context, attrs), View.OnClickListener {

    private var mListener: OnJumpListener? = null

    private val picker: MaterialNumberPicker

    init {
        this.width = ViewGroup.LayoutParams.FILL_PARENT
        this.height = ViewGroup.LayoutParams.WRAP_CONTENT
        this.setBackgroundDrawable(BitmapDrawable())// 这样设置才能点击屏幕外dismiss窗口
        this.isOutsideTouchable = true
        this.animationStyle = R.style.popwindow_anim_style

        val mLayoutInflater = LayoutInflater.from(context)
        val rootView = mLayoutInflater.inflate(R.layout.page_picker_view, null)
        rootView.findViewById(R.id.btCancel).setOnClickListener(this)
        rootView.findViewById(R.id.btFirst).setOnClickListener(this)
        rootView.findViewById(R.id.btJump).setOnClickListener(this)
        rootView.findViewById(R.id.btLast).setOnClickListener(this)
        picker = rootView.findViewById(R.id.picker)
        contentView = rootView
    }

    internal fun jump() {
        val page = picker.value
        if (mListener != null) {
            mListener!!.OnJump(page)
        }
        dismiss()
    }

    internal fun end() {
        val page = picker.maxValue
        if (mListener != null) {
            mListener!!.OnJump(page)
        }
        dismiss()
    }

    internal fun first() {
        val page = picker.minValue
        if (mListener != null) {
            mListener!!.OnJump(page)
        }
        dismiss()
    }

    fun setMin(min: Int) {
        picker.minValue = min
    }

    fun setMax(max: Int) {
        picker.maxValue = max
    }

    fun setValue(value: Int) {
        picker.value = value
    }

    fun setOnJumpListener(listener: OnJumpListener) {
        mListener = listener
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.btCancel -> dismiss()
            R.id.btFirst -> first()
            R.id.btLast -> end()
            R.id.btJump -> jump()
        }
    }

    interface OnJumpListener {
        fun OnJump(page: Int)
    }
}
